package com.nuvsoft.android.nuvgamenet.example;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.nuvsoft.android.nuvgamenet.NuvGameNetApplication;
import com.nuvsoft.android.nuvgamenet.R;
import com.nuvsoft.android.nuvgamenet.R.id;
import com.nuvsoft.android.nuvgamenet.R.layout;
import com.nuvsoft.android.nuvgamenet.net.BroadcastHandler;
import com.nuvsoft.android.nuvgamenet.net.ConnectionListener;

public class Buzzer extends Activity {
	private static final String LOG_TAG = Buzzer.class.getSimpleName();
	BroadcastHandler b;
	NuvGameNetApplication ba;

	private TextView tv;
	private Handler messageHandler;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		ba = (NuvGameNetApplication) this.getApplication();

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		b = new BroadcastHandler((NuvGameNetApplication)getApplication());
		b.addBroadcastListener(new ConnectionListener() {
			@Override
			public void onReceiveMessage(String message) {
				Log.v("RECEIVE", "RECEIVED: " + message);
				Message msg = new Message();
				msg.getData().putString("message", message);
				messageHandler.sendMessage(msg);
			}

		});
		b.startListening();

		tv = (TextView) Buzzer.this.findViewById(R.id.TextView01);
		messageHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				tv.setText(System.currentTimeMillis() + "\n\t"
						+ msg.getData().getString("message"));
			}
		};

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10000);
						Log.v("SEND", "SENDING MESSAGE");
						if (!getBroadcastHandler().sendData(
								String.format("%s,%s", ba.getHardwareID(), ba
										.getLocalIpAddress()))) {
							Log.v(LOG_TAG, "SEND FAILED!");
						} else {
							Log.v(LOG_TAG, "SEND SUCCEEDED!");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

		}).start();
	}

	public BroadcastHandler getBroadcastHandler() {
		return b;
	}
}